﻿using System;
using System.Windows.Forms;
using UnionnetClient.Model;

namespace UnionnetClient
{
	class Controller
	{
		public Controller(MainForm mainForm)
		{
			this.mainForm = mainForm;
			AppEnvironment.StateChanged += StateChanged;
		}

		static public void Configure(Form settingsForm)
		{
			if (DialogResult.OK == settingsForm.ShowDialog())
			{
				
			}
			settingsForm.Close();
		}

		static public void GotoSelfService()
		{
			string addr = (string)AppEnvironment.Settings[SettingsProperty.ServiceAddress];
			if (addr != null)
			{
				System.Diagnostics.Process.Start(addr);
			}
		}

		#region StateMachine

		public void Login()
		{
			AppEnvironment.CurrentState.Login();
		}

		public void Logout()
		{
			AppEnvironment.CurrentState.Logout();
		}

		public void Exit()
		{
			AppEnvironment.CurrentState.Exit();
		}

		public StateBase CurrentState
		{
			get { return AppEnvironment.CurrentState; }
		}

		private void StateChanged(object sender, EventArgs e)
		{
			if (!(AppEnvironment.CurrentState is LoginedState)) //非登陆状态
			{
				//mainForm.ToolStripLogin.Enabled = true;
				//mainForm.ToolStripLogout.Enabled = false;
				mainForm.SetToolStripEnable(mainForm.ToolStripLogin, true);
				mainForm.SetToolStripEnable(mainForm.ToolStripLogout, false);
				mainForm.NotifyIcon.Icon = Properties.Resources.browser_gray;
				mainForm.NotifyIcon.Text = "# 聚友登陆客户端 #\n网络状态 : 未连接";
			}
			else //登陆状态
			{
				//mainForm.ToolStripLogin.Enabled = false;
				mainForm.SetToolStripEnable(mainForm.ToolStripLogin, false);
				mainForm.NotifyIcon.Icon = Properties.Resources.browser;

				if (AppEnvironment.CurrentState is UnknownLoginedState)//通过其他方式已经连接上互联网
				{
					//mainForm.ToolStripLogout.Enabled = false;
					mainForm.SetToolStripEnable(mainForm.ToolStripLogout, false);
					mainForm.NotifyIcon.Text = "# 聚友登陆客户端 #\n网络状态 : 已连接\n登陆模式 : 未知";
				}
				else
				{
					StateBase state = AppEnvironment.CurrentState;
					//mainForm.ToolStripLogout.Enabled = true;
					mainForm.SetToolStripEnable(mainForm.ToolStripLogout, true);
					mainForm.NotifyIcon.Text = string.Format("# 聚友登陆客户端 #\n网络状态 : 已连接\n登陆模式 : {0}VPN", state is VpnState ? "" : "非");

					mainForm.NotifyIcon.ShowBalloonTip(5000, "登入成功",
						string.Format("登入时间 : {0}\n断线方式 : {1}", DateTime.Now.ToLongTimeString(), state is VpnState ? "自动侦测" : "手动注销"),
						ToolTipIcon.Info);
				}
			}
		}

		#endregion

		private MainForm mainForm;
	}
}
